﻿using System;
using System.Text;
using System.IO;
using Microsoft.AspNetCore.Http;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats.Png;
using SixLabors.ImageSharp.Processing;
using System.Net.Http;

namespace Common
{
    /// <summary>
    /// 保存图片, 如果图片之前已上传, 删除旧图片
    /// </summary>
    public class ImagesTools
    {
        private static HttpClient client;

        static ImagesTools()
        {
            if (client == null)
            {
                client = new HttpClient();
                client.DefaultRequestHeaders.Accept.TryParseAdd("text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
                client.DefaultRequestHeaders.AcceptEncoding.TryParseAdd("gzip, deflate, br");
                client.DefaultRequestHeaders.UserAgent.TryParseAdd("Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36");
            }
        }

        /// <summary>
        /// 下载图片返回磁盘文件的相对路径
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string DownloadImg(string url)
        {
            var root = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot");
            var downloadFolder = "download";
            var imgFolder = "image";
            var dateFolder = DateTimeOffset.UtcNow.ToString("yyyy-MM-dd");
            var ext = url.Substring(url.LastIndexOf('.'));
            var name = Guid.NewGuid().ToString("N");
            var filename = $"{name}{ext}";

            var filePath = Path.Combine(root, downloadFolder, imgFolder, dateFolder, filename);

            if (!Directory.Exists(root))
            {
                Directory.CreateDirectory(root);
            }
            var fi = new FileInfo(filePath);
            if (!fi.Directory.Exists)
            {
                Directory.CreateDirectory(fi.DirectoryName);
            }

            using (var fs = File.OpenWrite(filePath))
            {
                var stream = client.GetStreamAsync(url).GetAwaiter().GetResult();
                stream.CopyTo(fs);
            }

            return $"/{downloadFolder}/{imgFolder}/{dateFolder}/{filename}";
        }

    }
}
